package persistencia;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;


public class PoolConnection
{
	private Vector <Connection> connections = new Vector<Connection>();
	private String jdbc;
	private String servidor;
	private String usuario;
	private String password;
	private int cantCon;
	private static PoolConnection pool;
	private PoolConnection()
	{
		
		jdbc=new String("jdbc:sqlserver://");
		servidor=new String("localhost:1433");
		usuario=new String("programacion");
		password=new String("q1w2e3");
		cantCon=20;
		for (int i= 0; i< cantCon;i++)
			connections.add(connect());
	}
	
	public static PoolConnection getPoolConnection()
	{
		if (pool== null)
			pool =new PoolConnection();
		return pool;
	}
	private Connection connect()
	{
		try
		{
			//Setear driver
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //SQL server
			String dbConnectString = jdbc + servidor; 
			Connection con = DriverManager.getConnection (dbConnectString, usuario, password);
			
			
			//para conectar al SQLITE
			/*Class.forName("org.sqlite.JDBC");
            Connection con = DriverManager.getConnection ("jdbc:sqlite:c:\\Documents and Settings\\FHUBER\\workspace\\Seminario\\db\\seminario.s3db");
            */
            return con;
		}
		catch (SQLException e)
		{
			System.out.println("Mensaje Error: " + e.getMessage());
			System.out.println("Stack Trace: " + e.getStackTrace());
			return null;
		}
		catch (Exception ex)
		{
			System.out.println("Mensaje Error: " + ex.getMessage());
			System.out.println("Stack Trace: " + ex.getStackTrace());
			return null;
		}
	}
	public void closeConnections()
	{
		for (int i=0; i<connections.size();i++)
		{
			try
			{
				connections.elementAt(i).close();
			}
			catch(Exception e)
			{
				System.out.println("Mensaje Error: " + e.getMessage());
				System.out.println("Stack Trace: " + e.getStackTrace());
			}
		}
	}
	public  Connection getConnection()
	{
		Connection c = null;
		if (connections.size()>0)
			c = connections.remove(0);
		else
		{
			c = connect();
			System.out.println("Se ha creado una nueva conexion fuera de los parametros de configuracion");
		}
		return c;
	}
	public void releaseConnection(Connection c)
	{
		connections.add(c);
	}
}
